<!-- 新增/编辑证书模板1 --> 
<template>
  <div>
    <el-dialog
      :title="title"
      :visible="visible"
      width="800px"
      @close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
        <!-- 证书模板名称 -->
        <el-form-item label="证书模板名称" prop="name">
          <el-input
            v-model="formData.name"
            style="width: 60%"
            placeholder="请输入证书模板名称"
          />
        </el-form-item>

        <!-- 培训项目 -->
        <el-form-item label="培训项目" prop="trainingProjectId">
          <el-cascader
            v-model="formData.trainingProjectId"
            :options="projectOptions"
            :props="{
              checkStrictly: true,
              emitPath: false, //只传入子节点的id
              value: 'id',
              label: 'label',
              children: 'children',
            }"
            placeholder="请选择培训项目"
            style="width: 60%"
            clearable
          />
        </el-form-item>

        <!-- 纸张类型 -->
        <el-form-item label="纸张类型" prop="paperType">
          <el-select
            v-model="formData.paperType"
            placeholder="请选择纸张类型"
            style="width: 60%"
          >
            <el-option label="普通证书" value="normal" />
            <el-option label="荣誉证书" value="honor" />
            <el-option label="培训结业证" value="training" />
          </el-select>
        </el-form-item>

        <!-- 纸张尺寸 -->
        <el-form-item label="纸张尺寸" prop="paperSize">
          <el-select
            v-model="formData.paperSize"
            placeholder="请选择纸张尺寸"
            style="width: 60%"
            @change="handlePaperSizeChange"
          >
            <el-option label="A4(297mm×210mm)" value="A4" />
            <el-option label="A3(420mm×297mm)" value="A3" />
            <el-option label="B5(182mm×257mm)" value="B5" />
            <el-option
              v-if="customPaperOption"
              :label="customPaperOption.label"
              :value="customPaperOption.value"
            />
          </el-select>
          <el-button type="text" size="small" @click="openCustomSizeDialog"
            >自定义纸张</el-button
          >
        </el-form-item>

        <!-- 证书字段 -->
        <el-form-item label="证书字段" prop="fields">
          <el-checkbox-group v-model="formData.fields">
            <el-checkbox
              v-for="field in certificateFields"
              :key="field.value"
              :label="field.value"
            >
              {{ field.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 证书背景 -->
        <el-form-item label="证书背景" prop="backgroundImage">
          <div style="display: flex; align-items: flex-start; gap: 20px">
            <div>
              <el-upload
                ref="upload"
                :limit="1"
                accept=".jpg,.jpeg,.png"
                :action="formData.upload.url"
                :headers="formData.upload.headers"
                :file-list="formData.upload.fileList"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                :before-upload="beforeUpload"
                :on-change="handleFileChange"
                :on-remove="handleRemove"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >

                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </div>

            <div style="flex: 1; text-align: center">
              <div v-if="previewUrl" class="image-preview">
                <img
                  :src="previewUrl"
                  alt="证书背景预览"
                  style="max-width: 200px; max-height: 300px"
                />
                <el-button type="text" @click="removePreview">删除</el-button>
              </div>
              <div v-else class="placeholder">
                <i class="el-icon-picture-outline"></i>
                <p>点击上传或拖拽图片</p>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button>
      </div>
    </el-dialog>

    <CustomPaperSizeDialog
      @confirm="handleCustomConfirm"
      :visible.sync="showCustomDialog"
    />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { projectTreeSelect } from "@/api/training/projects";
import { createInitialTemplateData } from "@/components/Certificate/template/templateStructure";
import CustomPaperSizeDialog from "@/components/Certificate/template/CustomPaperSizeDialog.vue";

export default {
  name: "CertificateTemplateDialog",
  components: {
    CustomPaperSizeDialog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 编辑时传入已有数据
    editData: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      formData: {
        name: "",
        trainingProjectId: "",
        fields: [],
        backgroundImage: "",
        // 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/file/upload",
          // url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: [],
        },
        paperType: "", // 新增
        paperSize: "", // 新增
        customSize: null,
      },
      previewUrl: "",
      projectOptions: [], // 从接口获取
      certificateFields: [
        { label: "姓名", value: "name" },
        { label: "证件编号", value: "idNumber" },
        { label: "培训项目", value: "trainingProject" },
        { label: "有效年限", value: "validYears" },
        { label: "发证日期", value: "issueDate" },
        { label: "起始有效期", value: "startDate" },
        { label: "截止有效期", value: "endDate" },
      ],
      rules: {
        name: [
          { required: true, message: "请输入证书模板名称", trigger: "blur" },
        ],
        trainingProjectId: [
          { required: true, message: "请选择培训项目", trigger: "change" },
        ],
        fields: [
          {
            required: true,
            message: "请选择至少一个证书字段",
            trigger: "change",
          },
        ],
        backgroundImage: [
          { required: true, message: "请上传证书背景", trigger: "change" },
        ],
        paperType: [
          { required: true, message: "请选择纸张类型", trigger: "change" },
        ],
        paperSize: [
          { required: true, message: "请选择纸张尺寸", trigger: "change" },
        ],
      },
      // 查询参数
      queryParams: {
        projectId: "",
      },
      // 自定义纸张弹窗
      showCustomDialog: false,
      customPaperOption: null,
      selectedFile: null, //  跟踪选中的文件
      tempUrl: null,
    };
  },
  computed: {
    title() {
      return this.editData ? "编辑证书模板" : "新增证书模板";
    },
  },
  methods: {
    beforeUpload(file) {
      const isImage = file.type.includes("image");
      const isLt500K = file.size / 1024 < 500;

      if (!isImage) {
        this.$message.error("只能上传图片格式文件!");
        return false;
      }
      if (!isLt500K) {
        this.$message.error("上传文件大小不能超过 500KB!");
        return false;
      }

      // 设置选中的文件
      this.selectedFile = file;
      return true;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.formData.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.formData.upload.isUploading = false;

      console.log("上传的文件：", response.data.url);

      if (response.code === 200) {
        // 保存服务器返回的文件路径
        this.formData.backgroundImage = response.data.url;
        this.tempUrl = response.data.url;
        this.$message.success("上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
        this.handleRemove();
      }
    },
    handleFileError(err, file, fileList) {
      this.formData.upload.isUploading = false;
      this.$message.error("上传失败");
      this.handleRemove();
    },
    openCustomSizeDialog() {
      this.showCustomDialog = true;
    },
    handleCustomConfirm(data) {
      const label = `${data.name} (${data.length}mm×${data.width}mm)`;

      this.formData.customSize = label;
      // 标识自定义尺寸
      this.formData.paperSize = "custom";
      // 保存自定义选项用于显示
      this.customPaperOption = {
        label: label,
        value: "custom",
      };

      this.showCustomDialog = false;
    },

    handlePaperSizeChange(value) {
      // 当用户选择纸张尺寸时，重置自定义尺寸数据
      if (value !== "custom") {
        this.formData.customSize = null;
      }
    },
    initForm() {
      this.resetForm();
      if (this.editData) {
        this.formData = {
          ...this.editData,
          upload: {
            isUploading: false,
            headers: { Authorization: "Bearer " + getToken() },
            url: process.env.VUE_APP_BASE_API + "/file/upload",
            fileList: [],
            ...this.editData.upload,
          },
        };
        console.log("this.formData.upload.url:", this.formData.upload.url);
        this.previewUrl = this.formData.upload.url;
        // 如果有编辑数据且包含背景图片路径，则显示预览
        if (this.editData.backgroundImage) {
          // 这里假设backgroundImage是服务器上的文件路径
          this.previewUrl =
            process.env.VUE_APP_BASE_API + this.editData.backgroundImage;
        }
      }
    },
    resetForm() {
      this.$refs["form"].resetFields();
      this.formData = {
        name: "",
        trainingProjectId: "",
        fields: [],
        backgroundImage: "",
        upload: {
          isUploading: false,
          headers: { Authorization: "Bearer " + getToken() },
          url: process.env.VUE_APP_BASE_API + "/file/upload",
          fileList: [],
        },
        paperType: "",
        paperSize: "",
        customSize: null,
      };
      this.previewUrl = "";
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.resetForm();
    },
    handleFileChange(file, fileList) {
      // 文件选择后的预览
      if (file.raw) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewUrl = e.target.result;
        };
        reader.readAsDataURL(file.raw);
      }
    },
    handleRemove() {
      this.previewUrl = "";
      this.formData.backgroundImage = "";
      this.selectedFile = null;
      this.$refs.upload.clearFiles();

      // 重新触发验证
      this.$nextTick(() => {
        this.$refs.form.validateField("backgroundImage");
      });
    },
    removePreview() {
      this.handleRemove();
    },
    nextStep() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 创建与查看组件一致的数据结构
          const templateData = {
            basicInfo: {
              name: this.formData.name,
              trainingProjectId: this.formData.trainingProjectId,
              paperType: this.formData.paperType,
              paperSize: this.formData.paperSize,
              backgroundImage: this.tempUrl,
              upload: this.formData.upload,
            },
            fields: {
              optionalFields: this.certificateFields.map((field) => ({
                ...field,
                selected: this.formData.fields.includes(field.value),
              })),
              customFields: [],
            },
            fieldFormats: {}, // 初始为空，将在编辑器中填充
          };

          this.$emit("success", templateData);
        }
      });
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
        // this.projectOptions = this.flattenTree(response.data);
      });
    },
    // flattenTree(treeData) {
    //   let result = [];
    //   treeData.forEach((item) => {
    //     result.push({
    //       id: item.id,
    //       label: item.label,
    //     });
    //     if (item.children && item.children.length > 0) {
    //       result = result.concat(this.flattenTree(item.children));
    //     }
    //   });
    //   return result;
    // },
  },
  created() {
    this.getProjectTree();
  },

  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.initForm();
        });
      }
    },
  },
};
</script>

<style scoped>
.image-preview {
  border: 1px solid #dcdfe6;
  padding: 10px;
  margin-top: 10px;
  text-align: center;
}

.placeholder {
  border: 1px dashed #dcdfe6;
  padding: 40px;
  text-align: center;
  color: #999;
  cursor: pointer;
}
</style>

